import 'package:card_swiper/card_swiper.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/custom_dot_swiper.dart';
import 'package:cbec_app/components/common/custom_fraction_swiper.dart';
import 'package:cbec_app/components/common/custom_rect_swiper.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///店铺装修-图片广告
class DecorationAdImage extends StatefulWidget {
  ///图片广告配置
  final Map<String, dynamic> info;
  const DecorationAdImage({super.key, required this.info});

  @override
  State<StatefulWidget> createState() {
    return _DecorationAdImageState();
  }
}

class _DecorationAdImageState extends State<DecorationAdImage> {
  @override
  Widget build(BuildContext context) {
    return getBox();
  }

  ///获取容器
  Widget getBox() {
    switch (widget.info['show_method']) {
      case '2': //轮播海报
        return Container(
            margin: EdgeInsets.only(left: getMargin(), right: getMargin()),
            // transform: Matrix4.translationValues(0, -40, 0),
            width: getUseWidth(),
            height: getUseWidth() / Tools.getImgScale(widget.info['sub_entry']),
            child: Swiper(
              autoplay: true,
              itemCount: getList().length,
              itemBuilder: (BuildContext context, int index) {
                return adItem(getList()[index], getUseWidth(), height: getUseWidth() / Tools.getImgScale(widget.info['sub_entry']));
              },
              autoplayDisableOnInteraction: true,
              autoplayDelay: widget.info['swipe_time'],
              loop: true,
              pagination: indicatorStyle(),
            ));
      case '3': //双层轮播
        return Container(
            margin: EdgeInsets.only(left: getMargin(), right: getMargin()),
            width: getUseWidth(),
            height: getUseWidth() / Tools.getImgScale(widget.info['sub_entry']),
            child: FutureBuilder(
              future: Future.wait(getList().map((item) => precacheImage(item['image_url'], context))),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  return Swiper(
                    autoplay: true,
                    autoplayDisableOnInteraction: true,
                    autoplayDelay: widget.info['swipe_time'],
                    itemBuilder: (context, index) {
                      return adItem(getList()[index], getUseWidth(), height: getUseWidth() / Tools.getImgScale(widget.info['sub_entry']));
                    },
                    itemCount: getList().length,
                    pagination: indicatorStyle(),
                  );
                }
                return emptyWidget();
              },
            ));
      case '4': //横向滚动
        return Container(
          margin: EdgeInsets.only(left: getMargin()),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: getList().map((item) => adItem(item, getImgWidth())).toList(),
            ),
          ),
        );
      case '1': //一行一个
      default:
        return Container(
            color: Tools.fromHex('#f4f4f4'),
            margin: EdgeInsets.only(left: getMargin(), right: getMargin()),
            child: Wrap(
              direction: Axis.vertical,
              spacing: (widget.info['border_width'] as int).toDouble(),
              children: getList().map((item) => adItem(item, getUseWidth())).toList(),
            ));
    }
  }

  ///获取页面边距
  double getMargin() {
    return double.parse(widget.info['page_margin'].toString());
  }

  ///获取可用宽度
  double getUseWidth() {
    return 375.w - getMargin() * 2;
  }

  ///获取配置列表
  List getList() {
    return widget.info['sub_entry'] as List;
  }

  ///获取图片宽度
  double getImgWidth() {
    //(总宽度-左侧margin宽度-图片间距宽度-40)/屏显数量-1
    return (375.w - getMargin() - (getList().length - 1) * widget.info['border_width'] - 40) / getShowCount();
  }

  ///获取屏显数量
  double getShowCount() {
    double count = double.parse(widget.info['count']) - 1;
    return count > 0 ? count : 1;
  }

  ///图片广告item
  Widget adItem(Map<String, dynamic> item, double width, {double? height}) {
    // print('图片广告item ===== $item');

    switch (widget.info['show_method']) {
      case '4': //横向滚动
        return BaseInteractive(
          childWidget: Row(
            children: [
              Stack(
                children: [
                  BaseImage(
                    url: item['image_url'],
                    width: width,
                    height: height,
                    borderRadius: BorderRadius.circular(getRadius()),
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: Container(
                      width: width,
                      height: 36,
                      alignment: Alignment.center,
                      color: item['title'] != '' ? Colors.black.withOpacity(0.8) : Colors.transparent,
                      // transform: Matrix4.translationValues(0, -36, 0),
                      child: SizedBox(
                        width: width,
                        child: Text(
                          item['title'] ?? '',
                          style: setTextStyle(14, FontWeight.bold, Colors.white),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                width: (widget.info['border_width'] as int).toDouble(),
              )
            ],
          ),
          onClick: () {
            Tools.jumpPage(item);
          },
        );
      case '1': //一行一个
      case '2': //轮播
      case '3': //双重轮播
      default:
        return BaseInteractive(
          childWidget: Stack(
            children: [
              BaseImage(
                url: item['image_url'],
                width: width,
                height: height,
                borderRadius: BorderRadius.circular(getRadius()),
              ),
              Positioned(
                  bottom: 0,
                  left: 0,
                  child: Container(
                    width: width,
                    height: 36,
                    alignment: Alignment.center,
                    color: item['title'] != '' ? Colors.black.withOpacity(0.8) : Colors.transparent,
                    child: SizedBox(
                      width: width,
                      child: Text(
                        item['title'] ?? '',
                        style: setTextStyle(14, FontWeight.bold, Colors.white),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ))
            ],
          ),
          onClick: () {
            Tools.jumpPage(item);
          },
        );
    }
  }

  ///轮播指示器样式
  SwiperPlugin indicatorStyle() {
    switch (widget.info['indicator']) {
      case '2':
        return const SwiperPagination(builder: CustomRectSwiper());
      case '3':
        return const SwiperPagination(alignment: Alignment.bottomRight, margin: EdgeInsets.only(right: 20), builder: CustomFractionSwiper());
      case '4':
        return const SwiperPagination(alignment: Alignment.bottomRight, margin: EdgeInsets.only(right: 20), builder: CustomFractionSwiper(bgColor: ThemeConfig.sectionTextColor));
      case '1':
      default:
        return const SwiperPagination(builder: CustomDotSwiper());
    }
  }

  ///获取图片圆角
  double getRadius() {
    return widget.info['corner_type'] == '1' ? 0.0 : 3.0;
  }
}
